#include "KeyCountServer.h"

namespace KeyCountServer {

bool ClientLocal::isExist(char *username, char *password)
{
    DIR *dir = opendir(username);
    if (dir == NULL)
        return 0;
    char path[MAX_LEN + 10];
    sprintf(path, "%s/passwd", username);
    int fd = open(path, O_RDONLY);
    if (fd < 0)
    {
        LOG("open %s/passwd error\n", username);
        return 0;
    }
    read(fd, password, MAX_LEN);
    close(fd);
    return 1;
}

bool ClientLocal::createUser(char *username, char *password)
{
    if (mkdir(username, 0755) < 0)
    {
        LOG("mkdir %s error\n", username);
        return 0;
    }
    char path[MAX_LEN + 10];
    sprintf(path, "%s/passwd", username);
    int fd = creat(path, 0644);
    if (fd < 0)
    {
        LOG("create %s/passwd error\n", username);
        return 0;
    }
    write(fd, password, strlen(password));
    close(fd);
    return 1;
}

bool ClientLocal::saveData(char *username, char *data, int len)
{
    char path[MAX_LEN + 10];
    sprintf(path, "%s/data", username);
    int fd = creat(path, 0644);
    if (fd < 0)
    {
        LOG("create %s/data error\n", username);
        return 0;
    }
    write(fd, data, len);
    close(fd);
    return 1;
}

bool ClientLocal::loadData(char *username, char * &data, int *len)
{
    char path[MAX_LEN + 10];
    sprintf(path, "%s/data", username);
    int fd = open(path, O_RDONLY);
    if (fd < 0)
    {
        *len = 0;
        return 0;
    }
    struct stat fStat;
    stat(path, &fStat);
    *len = fStat.st_size;
    data = new char[*len];
    read(fd, data, *len);
    close(fd);
    return 1;
}

}
